/**
 * 数据探索-通用统计报表服务
 */

// 导出表格
function downLoadTableToExcel(excelBody, fileName) {
    var uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(excelBody);
    var a = document.createElement("a");
    var time = new Date().toLocaleString('chinese', {
        hour12: false
    }).replace(/\/|:| /g, '');
    a.download = fileName + time + '.csv';
    a.href = uri;
    a.click();
}

// 刷新表格
function freshTableHtml(html) {
    var myTableHtml = '<div id="div_container" style="text-align:center;margin:0 auto;"><div id="my_div" class="fakeContainer first_div" style="padding:1px"><table border="1" id="demoTable" style="margin-top:5px;border-collapse: collapse;">';
    myTableHtml += html;
    myTableHtml += '</table></div></div>';
    $('#myTable').html('');
    $('.daochubiaoge').hide();
    $('#myTable').html(myTableHtml);
    $('.daochubiaoge').show();
    afterCreateTable();
}

// 创建表格后调用js
function afterCreateTable() {
    // 调用superTable
    new superTable("demoTable", {
        cssSkin: "sDefault",
        fixedCols: 1, //固定几列
        headerRows: 1, //头部固定行数
        onStart: function () {
            this.start = new Date();
        },
        onFinish: function () {}
    });
    //这个宽度是容器宽度，不同容器宽度不同
    if ($('.sFData').width() < $('#myTable').width()) {
        $("#div_container").width($('.sFData').width() + 2)
    } else {
        $("#div_container").width($('#myTable').width() + 2)
    }
    $(".fakeContainer").height($('#myTable').height()); //这个高度是整个table可视区域的高度，不同情况高度不同
    $(".sData").addClass('scroll');
    //.sData是调用superTables.js之后页面自己生成的  这块就是出现滚动条 达成锁定表头和列的效果
    if ($('.sFData').width() > $('#myTable').width()) {
        $(".sData").width($('#div_container').width() - $('#left-top').outerWidth() - 2); //这块的宽度是用$("#div_container")的宽度减去锁定的列的宽度
    } else {
        $(".sData").width($('.sFData').width() - $('#left-top').outerWidth())
    }
    if ($('.sFData').height() > $('#myTable').height()) {
        $(".sData").height($('#div_container').height() - $('#left-top').outerHeight() - 2); //这块的高度是用$("#div_container")的高度减去锁定的表头的高度
    } else {
        $(".sData").height($('.sFData').height() - $('#left-top').outerHeight())
    }
    //目前谷歌  ie8+  360浏览器均没问题  有些细小的东西要根据项目需求改
    //有兼容问题的话可以在下面判断浏览器的方法里写
    if (navigator.appName == "Microsoft Internet Explorer" && navigator.appVersion.match(/9./i) == "9.") { //alert("IE 9.0");
    } else if (!!window.ActiveXObject || "ActiveXObject" in window) { //alert("IE 10");

    } else { //其他浏览器
        //alert("其他浏览器");
    }
}

// 判断数据格式
function judgeValue(value) {
    return value == '' || value == ' ' || value == undefined ? 'null' : value;
}

// 1-1表格
function createTable(yData, datavalue) {
    if (yData.length == 0 || datavalue.length == 0) {
        $('#myTable').html('<div style="text-align: center;">无数据</div>');
        return;
    }
    //console.log(yData,datavalue)
    // 首行表头
    var html = '<tr><th id="left-top"></th><th class="biaotou center">' + $('#ul4 li').eq(0).html() + '</th></tr>';
    // 导出表格str
    var str = ',' + $('#ul4 li').eq(0).html() + '\n';
    yData.forEach(function (x, index) {
        console.log(x, datavalue[index]);
        html += '<tr><td>' + judgeValue(x) + '</td><td>' + judgeValue(datavalue[index]) + '</td><tr>';
        str += judgeValue(x) + '\t,' + judgeValue(datavalue[index]) + '\t\n';
    })
    freshTableHtml(html);
    $('.daochubiaoge').off('click').on('click', function () {
        downLoadTableToExcel(str, '表格');
    })
}

// 1-n表格
function createTable3(yData, datavalue) {
    if (yData[0].length == 0 || datavalue.length == 0) {
        $('#myTable').html('<div style="text-align: center;">无数据</div>');
        return;
    }
    console.log(yData, datavalue)
    // 首行表头
    var html = '<tr><th id="left-top"></th>';
    var str = ''
    $('#ul4 li').each(function (index, item) {
        html += '<th class="biaotou center">' + $(item).html() + '</th>';
        str += ',' + $(item).html() + '\t'
    })
    html += '</tr>';
    str += '\n';

    yData[0].forEach(function (x, index) {
        html += '<tr><td>' + judgeValue(x) + '</td>';
        str += judgeValue(x) + '\t';
        datavalue.forEach(function (item, num) {
            html += '<td>' + judgeValue(datavalue[num][index]) + '</td>';
            str += ',' + judgeValue(datavalue[num][index]) + '\t';
        })
        html += '</tr>';
        str += '\n';
    })
    freshTableHtml(html);
    $('.daochubiaoge').off('click').on('click', function () {
        downLoadTableToExcel(str, '表格');
    })
}

// 2-1表格
function createTable4(yData, datavalue, data) {
    if (data.length == 0) {
        $('#myTable').html('<div style="text-align: center;">无数据</div>');
        return;
    }
    //console.log(data);
    var colNameArr = [];
    var rowNameArr = [];
    var totalValueArr = [];
    // 遍历每行
    for (var key in data) {
        rowNameArr.push(judgeValue(key));
        var colValueArr = [];
        for (var i in data[key]) {
            //console.log(i, data[key][i]);
            var value = judgeValue(data[key][i]);
            if (colNameArr.indexOf(i) == -1) {
                colNameArr.push(i);
            }
            colValueArr[colNameArr.indexOf(i)] = value;
        }
        totalValueArr.push(colValueArr);
    }
    //console.log(colNameArr, totalValueArr)
    var colLength = colNameArr.length;

    // 表格html
    var myTableHtml = '<tr>';
    // 导出表格str
    var str = '';
    // 左 右
    myTableHtml += '<th id="left-top" class="three"><span class="title1">' + $('#ul3 li').eq(0).html() + '</span><span class="title3">' + $('#ul3 li').eq(1).html() + '</span></th>';
    str += $('#ul3 li').eq(0).html() + '\\' + $('#ul3 li').eq(1).html();
    // 首行表头
    colNameArr.forEach(function (x, index) {
        myTableHtml += '<th class="biaotou center">' + judgeValue(x) + '</th>';
        str += ',' + judgeValue(x);
    })
    myTableHtml += '</tr>';
    str += '\n';
    // 表格主体
    totalValueArr.forEach(function (x, index) {
        myTableHtml += '<tr>';
        // 左侧表头
        myTableHtml += '<td class="biaotou">' + judgeValue(rowNameArr[index]) + '</td>';
        str += judgeValue(rowNameArr[index]);
        for (var i = 0; i < colLength; i++) {
            if (totalValueArr[index][i]) {
                myTableHtml += '<td class="center">' + judgeValue(totalValueArr[index][i]) + '</td>';
                str += ',' + judgeValue(totalValueArr[index][i]) + '\t';
            } else {
                myTableHtml += '<td class="center"></td>';
                str += ',';
            }
        }
        myTableHtml += '</tr>';
        str += '\n';
    })
    freshTableHtml(myTableHtml);
    $('.daochubiaoge').off('click').on('click', function () {
        downLoadTableToExcel(str, '表格');
    })
}

function FixTable(TableID, FixColumnNumber, width, height) {
    if ($("#" + TableID + "_tableLayout").length != 0) {
        $("#" + TableID + "_tableLayout").before($("#" + TableID));
        $("#" + TableID + "_tableLayout").empty();
    } else {
        $("#" + TableID).after("<div id='" + TableID + "_tableLayout' style='overflow:hidden;height:" + height + "px; width:" + width + "px;'></div>");
    }
    $('<div id="' + TableID + '_tableFix"></div>' +
        '<div id="' + TableID + '_tableHead"></div>' +
        '<div id="' + TableID + '_tableColumn"></div>' +
        '<div id="' + TableID + '_tableData"></div>').appendTo("#" + TableID + "_tableLayout");
    var oldtable = $("#" + TableID);
    var tableFixClone = oldtable.clone(true);
    tableFixClone.attr("id", TableID + "_tableFixClone");
    $("#" + TableID + "_tableFix").append(tableFixClone);
    var tableHeadClone = oldtable.clone(true);
    tableHeadClone.attr("id", TableID + "_tableHeadClone");
    $("#" + TableID + "_tableHead").append(tableHeadClone);
    var tableColumnClone = oldtable.clone(true);
    tableColumnClone.attr("id", TableID + "_tableColumnClone");
    $("#" + TableID + "_tableColumn").append(tableColumnClone);
    $("#" + TableID + "_tableData").append(oldtable);
    $("#" + TableID + "_tableLayout table").each(function () {
        $(this).css("margin", "0");
    });
    var HeadHeight = $("#" + TableID + "_tableHead thead").height();
    HeadHeight += 2;
    $("#" + TableID + "_tableHead").css("height", HeadHeight);
    $("#" + TableID + "_tableFix").css("height", HeadHeight);
    var ColumnsWidth = 0;
    var ColumnsNumber = 0;
    $("#" + TableID + "_tableColumn tr:last td:lt(" + FixColumnNumber + ")").each(function () {
        ColumnsWidth += $(this).outerWidth(true);
        ColumnsNumber++;
    });
    ColumnsWidth += 2;
    //if ($.browser.msie) {
    //    switch ($.browser.version) {
    //        case "7.0":
    //            if (ColumnsNumber >= 3) ColumnsWidth--;
    //            break;
    //        case "8.0":
    //            if (ColumnsNumber >= 2) ColumnsWidth--;
    //            break;
    //    }
    //}

    checkVersion();
    $("#" + TableID + "_tableColumn").css("width", ColumnsWidth);
    $("#" + TableID + "_tableFix").css("width", ColumnsWidth);
    $("#" + TableID + "_tableData").scroll(function () {
        $("#" + TableID + "_tableHead").scrollLeft($("#" + TableID + "_tableData").scrollLeft());
        $("#" + TableID + "_tableColumn").scrollTop($("#" + TableID + "_tableData").scrollTop());
    });
    $("#" + TableID + "_tableFix").css({
        "overflow": "hidden",
        "position": "relative",
        "z-index": "50",
        "background-color": "#0289ca"
    });
    $("#" + TableID + "_tableHead").css({
        "overflow": "hidden",
        "width": width - 17,
        "position": "relative",
        "z-index": "45",
        "background-color": "#0289ca"
    });
    $("#" + TableID + "_tableColumn").css({
        "overflow": "hidden",
        "height": height - 17,
        "position": "relative",
        "z-index": "40",
        "background-color": "#00a7dd"
    });
    $("#" + TableID + "_tableData").css({
        "overflow": "scroll",
        "width": width,
        "height": height,
        "position": "relative",
        "z-index": "35"
    });
    if ($("#" + TableID + "_tableHead").width() > $("#" + TableID + "_tableFix table").width()) {
        $("#" + TableID + "_tableHead").css("width", $("#" + TableID + "_tableFix table").width());
        $("#" + TableID + "_tableData").css("width", $("#" + TableID + "_tableFix table").width() + 17);
    }
    if ($("#" + TableID + "_tableColumn").height() > $("#" + TableID + "_tableColumn table").height()) {
        $("#" + TableID + "_tableColumn").css("height", $("#" + TableID + "_tableColumn table").height());
        $("#" + TableID + "_tableData").css("height", $("#" + TableID + "_tableColumn table").height() + 17);
    }
    $("#" + TableID + "_tableFix").offset($("#" + TableID + "_tableLayout").offset());
    $("#" + TableID + "_tableHead").offset($("#" + TableID + "_tableLayout").offset());
    $("#" + TableID + "_tableColumn").offset($("#" + TableID + "_tableLayout").offset());
    $("#" + TableID + "_tableData").offset($("#" + TableID + "_tableLayout").offset());
}

function strlen(str) {
    var len = 0;
    for (var i = 0; i < str.length; i++) {
        var c = str.charCodeAt(i);
        //单字节加1
        if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
            len++;
        } else {
            len += 2;
        }
    }
    return len;
}

function maxValue(arr) {
    let max = arr[0];
    for (let i = 0; i < arr.length - 1; i++) {
        max = max < arr[i + 1] ? arr[i + 1] : max
    }
    return max;
}

function getInternetExplorerVersion() {
    var rv = -1; // Return value assumes failure.

    if (navigator.appName == 'Microsoft Internet Explorer') {
        var ua = navigator.userAgent;
        var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
        if (re.exec(ua) != null)
            rv = parseFloat(RegExp.$1);
    }

    return rv;
}

function checkVersion() {
    var ver = getInternetExplorerVersion();
    if (ver > -1) {
        if (ver >= 8.0) {
            if (ColumnsNumber >= 2) ColumnsWidth--;
        } else {
            if (ColumnsNumber >= 3) ColumnsWidth--;
        }
    }
}